<?php

namespace app\admin\controller\order;

use app\admin\model\Shopmno;
use app\admin\model\Shoporderprofit;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\api\service\VbillService;
use app\common\controller\Backend;

/**
 * 团购券购买订单
 *
 * @icon fa fa-circle-o
 */
class Tuanorder extends Backend
{

    protected $relationSearch = true;
    protected $noNeedRight = ['refund'];

    /**
     * Tuanorder模型对象
     * @var \app\admin\model\Tuanorder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Tuanorder;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['user', 'tuan'])
                ->where($where)
                ->where('Tuanorder.status', "<>", 'paying')
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                if ($v['is_check'] == 1) {
                    $list[$k]['is_check'] = "异常";
                } else {
                    $list[$k]['is_check'] = "";

                }
            }

            $totalAmount = $this->model->where('status', 'not in', ['paying', 'refund'])->sum('amount');
            $todayAmount = $this->model->whereTime("create_time", 'today')->where('status', 'not in', ['paying', 'refund'])->sum('amount');
            $refundAmount = $this->model->whereTime("create_time", 'today')->where('status', 'refund')->sum('amount');

            $result = array("total" => $list->total(), "rows" => $list->items(), "extend" => ['one' => $totalAmount, 'two' => $todayAmount, 'three' => $refundAmount]);


            return json($result);
        }
        return $this->view->fetch();
    }

    public function refund()
    {
        $id = $this->request->param('id');

        $tuanModel = new \app\admin\model\Tuanorder();
        $tuan = $tuanModel->where('id', $id)->find();
        if ($tuan['status'] == 'refund') {
            $this->error("此订单已退款无需发起操作");
        }
        $userTuanModel = new Usertuan();
        $userTuan = $userTuanModel->where('order_id', $tuan['id'])->find();
        if (!$userTuan) {
            $this->error('用户团购券不存在');
        }

        $mnoModel = new Shopmno();
        $shopMno = $mnoModel->where('shop_id',$tuan['shop_id'])->find();
        if(!empty($shopMno) && $shopMno == 100){
            $mno = $shopMno['mno'];
        }else{
            $mno = $this->mno;
        }
        $req = array();
        $req['mno'] = $mno;
        $req['ordNo'] = getOrderSn();
        $req['origOrderNo'] = $tuan['order_no'];
        $req['amt'] = $tuan['amount'];

        $vbillService = new VbillService();
        $ret = $vbillService->refund($req);
        $result = json_decode($ret, true);
        if ($result['code'] != '0000') {
            $this->error($result['msg']);
        }
        if ($result['respData']['bizCode'] != "0000") {
            $this->error($result['respData']['bizMsg']);
        }
        $isCheck = -1;
        if ($userTuan['status'] == 'used') {
            $isCheck = 1;
        }
        $userTuanModel->where('id', $userTuan['id'])->update(['status' => 'refund']);
        $tuanModel->where('id', $id)->update(['update_time' => time(), 'is_check' => $isCheck, 'status' => 'refund']);
        $shopOrderProfitModel = new Shoporderprofit();
        $shopOrderProfitModel->where('type', 'tuan')->where('order_id', $id)->delete();

        $userOrderProfitModel = new Userorderprofit();
        $userOrderProfitModel->where('type', 'tuan')->where('order_id', $id)->delete();


        $this->success('退款成功');

    }


}
